package ly.count.ohos.sdk;


import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.CommonEventSubscriber;

import java.net.URLDecoder;

/**
 * ADB Testing
 * adb shell
 * am broadcast -a com.ohos.vending.INSTALL_REFERRER --es "referrer" "countly_cid%3Dxxxxcidvaluexxxx%26countly_cuid%3Dxxxxcuidvaluexxxx"
 **/
//******************************************************************************
public class ReferrerReceiver extends CommonEventSubscriber {
    private static final String key = "referrer";
    private DatabaseHelper databaseHelper;
    private Context context;
    //--------------------------------------------------------------------------
    public String getReferrer() {
        // Return any persisted referrer value or null if we don't have a referrer.
        return databaseHelper.getPreferences(key).getString(key, null);
    }

    public static String getReferrer(Context context) {
        // Return any persisted referrer value or null if we don't have a referrer.
        return new DatabaseHelper(context).getPreferences(key).getString(key, null);
    }

    public void deleteReferrer() {
        // delete stored referrer.
        databaseHelper.getPreferences(key).delete(key).flush();
    }

    public static void deleteReferrer(Context context) {
        // delete stored referrer.
        new DatabaseHelper(context).getPreferences(key).delete(key).flush();
    }

    //--------------------------------------------------------------------------
    public ReferrerReceiver(Context context , CommonEventSubscribeInfo subscribeInfo) {
        super(subscribeInfo);
        this.context = context;
        databaseHelper = new DatabaseHelper(context);
    }


    //--------------------------------------------------------------------------


    @Override
    public void onReceiveEvent(CommonEventData commonEventData) {

        try {
            // Make sure this is the intent we expect - it always should be.
            Intent intent = commonEventData.getIntent();
            if ((null != intent) && (intent.getAction().equals("com.ohos.vending.INSTALL_REFERRER"))) {
                // This intent should have a referrer string attached to it.
                //String rawReferrer = intent.getStringExtra(key);
                String rawReferrer = intent.getStringParam(key);

                if (null != rawReferrer) {
                    // The string is usually URL Encoded, so we need to decode it.
                    String referrer = URLDecoder.decode(rawReferrer, "UTF-8");

                    // Log the referrer string.
                    if(Countly.sharedInstance().isInitialized()) {
                        Countly.sharedInstance().L.d("Referrer: " + referrer);
                    }

                    String[] parts = referrer.split("&");
                    String cid = null;
                    String uid = null;
                    for (String part : parts) {
                        if (part.startsWith("countly_cid")) {
                            cid = part.replace("countly_cid=", "").trim();
                        }
                        if (part.startsWith("countly_cuid")) {
                            uid = part.replace("countly_cuid=", "").trim();
                        }
                    }
                    String res = "";
                    if (cid != null) {
                        res += "&campaign_id=" + cid;
                    }
                    if (uid != null) {
                        res += "&campaign_user=" + uid;
                    }

                    if(Countly.sharedInstance().isInitialized()) {
                        Countly.sharedInstance().L.d("Processed: " + res);
                    }
                    // Persist the referrer string.
                    if (!res.equals("")) {
                        databaseHelper.getPreferences(key).putString(key, res).flush();
                    }
                }
            }
        } catch (Exception e) {
            if(Countly.sharedInstance().isInitialized()) {
                Countly.sharedInstance().L.d(e.toString());
            }
        }
    }
}